package xyz.coderl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;


/**
 * 字符工具类
 * 
 * @author sunyanlong
 */
public class StringUtilss
{


	public static String randomS()
	{
		return getUUID();
	}

	/**
	 * 
	 */
	public static String checkXmlChar(String data)
	{
		StringBuffer appender = new StringBuffer("");

		if (StringUtils.isNotBlank(data))
		{
			appender = new StringBuffer(data.length());

			for (int i = 0; i < data.length(); i++)
			{
				char ch = data.charAt(i);
				if (ch == 0x9 || ch == 0xA || ch == 0xD || ch >= 0x20 && ch <= 0xD7FF || ch >= 0xE000 && ch <= 0xFFFD) {
					appender.append(ch);
				}
			}
		}

		String result = appender.toString();
		result = result.replaceAll("\"","");  
		result = result.replaceAll(";","");
		result = result.replaceAll("'","");
		result = result.replaceAll("&","");
		result = result.replaceAll("#","");
		return result.replaceAll("]]>", "");
	}

	/**
	 * 获得一个UUID
	 * 
	 * @return String UUID
	 */
	public static String getUUID()
	{
		String s = UUID.randomUUID().toString();
		// 去掉“-”符号
		return s.substring(0, 8) + s.substring(9, 13) + s.substring(14, 18) + s.substring(19, 23) + s.substring(24);
	}

	/**
	 * 去字符串前后含有regex的字符
	 * 
	 * @param str
	 * @param regex
	 * @return String
	 */
	public static String checkString(String str, String regex)
	{
		int startIndex = 0;
		int endIndex = 0;
		if (regex.equals(str.substring(0, 1)))
		{
			startIndex = 1;
		}
		if (regex.equals(str.substring(str.length() - 1)))
		{
			endIndex = str.length() - 1;
		}
		else
		{
			endIndex = str.length();
		}
		String retStr = str.substring(startIndex, endIndex);
		return retStr;
	}

	/**
	 * 求文件扩展名
	 * 
	 * @param fileName
	 * @return String
	 */
	public static String extendFileName(String fileName)
	{
		String name = fileName.trim();
		if (name == null || name.equals(""))
		{
			return "";
		}

		String exeName = null;
		try
		{
			int zeroIndex = name.lastIndexOf(".");
			if (zeroIndex != -1)
			{
				exeName = name.substring(zeroIndex + 1, name.length());
				exeName = name.substring(name.lastIndexOf(".") + 1);
			}
			else
			{
				exeName = "";
			}
		}
		catch (Exception e)
		{
		}
		return exeName.toLowerCase();
	}

	/**
	 * 将特殊字符隔开的字符串拆成List
	 * 
	 * @param str
	 * @param delimiter
	 * @return List
	 */
	public static List split(String str, char delimiter)
	{
		ArrayList<String> parts = new ArrayList<String>();

		if ((str == null) || "".equals(str))
		{
			return parts;
		}

		int currentIndex;
		int previousIndex = 0;
		while ((currentIndex = str.indexOf(delimiter, previousIndex)) > 0)
		{
			String part = str.substring(previousIndex, currentIndex).trim();
			parts.add(part);
			previousIndex = currentIndex + 1;
		}
		parts.add(str.substring(previousIndex, str.length()).trim());
		return parts;
	}

	/**
	 * 将字符串按照正则表达式拆分成数组
	 * 
	 * @param str
	 * @param space
	 * @return String[]
	 */
	public static String[] split(String str, String space)
	{
		String str1 = str.trim();
		int i, s, k;
		k = space.length();
		for (i = 0; str1.indexOf(space) != -1; i++)
		{
			str1 = str1.substring(str1.indexOf(space) + k, str1.length());
		}
		int bound = i + 1;
		str1 = str;
		String array[] = new String[bound];
		array[0] = "";
		for (i = 0; str1 != ""; i++)
		{
			s = str1.indexOf(space);
			if (s != -1)
			{
				array[i] = str1.substring(0, s);
				str1 = str1.substring(s + k, str1.length());
			}
			else
			{
				array[i] = str1;
				str1 = "";
			}
		}
		return array;
	}

	/**
	 * 若字符为空或""返回一默认值
	 * 
	 * @param str
	 * @param defaultValue
	 * @return String
	 */
	public static String nullStrToDefau(String str, String defaultValue)
	{
		String retStr = "";
		if (str == null || "".equals(str) || str.equals("null"))
		{
			retStr = defaultValue;
		}
		else
		{
			retStr = str;
		}
		return retStr;
	}

	@SuppressWarnings("unchecked")
	public static void orderMap(List groupMapList)
	{
		// 排序 内部类
		Collections.sort(groupMapList, new Comparator<Entry<String, Double>>()
		{
			// double排序
			@Override
			public int compare(Entry<String, Double> o1, Entry<String, Double> o2)
			{
				return o2.getValue().compareTo(o1.getValue());
			}
		});
	}

	/**
	 * 文本域输入框回车空格等字符转换
	 * 
	 * @param value
	 * @return String
	 */
	public static String filter(String value)
	{

		if (value == null) {
			return ("");
		}

		StringBuffer result = new StringBuffer();
		for (int i = 0; i < value.length(); i++)
		{
			char ch = value.charAt(i);
			if (ch == '<') {
				result.append("&lt;");
			} else if (ch == '>') {
				result.append("&gt;");
			} else if (ch == '&') {
				result.append("&amp;");
			} else if (ch == '"') {
				result.append("&quot;");
			} else if (ch == '\r') {
				result.append("<BR>");
			} else if (ch == '\n')
			{
				if (i > 0 && value.charAt(i - 1) == '\r')
				{

				}
				else
				{
					result.append("<BR>");
				}
			}
			else if (ch == '\t') {
				result.append("&nbsp;&nbsp;&nbsp;&nbsp");
			} else if (ch == ' ') {
				result.append("&nbsp;");
			} else {
				result.append(ch);
			}
		}
		return (result.toString());
	}

	/* 将html格式转为字串 */
	public static String strToHtml(String s)
	{
		if (s == null || s.equals("")) {
			return "";
		}
		s = s.replaceAll("&amp;", "&");
		s = s.replaceAll("&lt;", "<");
		s = s.replaceAll("&gt;", ">");
		s = s.replaceAll("&nbsp;", "   ");
		s = s.replaceAll("<br/>", "\n");
		s = s.replaceAll("&#39", "'");
		return s;
	}

	/**
	 * 得到n位随机字符
	 *
	 * @return
	 */
	public static String randomStr()
	{
		String str1 = "123456789";
		String str2 = "";
		int len = str1.length() - 1;
		double r;
		for (int i = 0; i < 1; i++)
		{
			r = (Math.random()) * len;
			str2 = str2 + str1.charAt((int) r);
		}
		return str2;
	}

	public static String randomString()
	{
		// String str1 = "0123456789abcdefghijklmnopqrstuvwxyz";
		String str1 = "23456789abcdefghijkmnpqrstuvwxyz";
		String str2 = "";
		int len = str1.length() - 1;
		double r;
		for (int i = 0; i < 6; i++)
		{
			r = (Math.random()) * len;
			str2 = str2 + str1.charAt((int) r);
		}
		return str2;
	}

	/**
	 * 截取字符的指定的前几个+...
	 * 
	 * @param str
	 * @param byteLength
	 * @return String
	 */
	public static String getSubString(String str, int byteLength)
	{
		if (str == null || str.equals(""))
		{
			return "";
		}
		byteLength = byteLength * 2;
		try
		{
			if (str.getBytes().length < byteLength)
			{
				return str;
			}
			else
			{
				while (str.getBytes().length > (byteLength - 2))
				{
					str = str.substring(0, str.length() - 1);
				}
				StringBuffer sb = new StringBuffer(byteLength);
				sb.append(str).append("...");
				return sb.toString();
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * java实现：计算年龄。参数：出生日期、欲计算的生效日期。没过生日，则减一。
	 * 
	 * @param BirthDate
	 * @param designateformat
	 *          例:(yyyy-MM-dd)
	 * @return int
	 * @throws Exception
	 */
	public static int computeIssueAge(String BirthDate, String designateformat)
	{

		SimpleDateFormat formatter = new SimpleDateFormat(designateformat);

		Calendar birthCalendar = Calendar.getInstance();
		Calendar effectiveCalendar = Calendar.getInstance();
		int age = 0;
		try
		{
			Date birthDate = formatter.parse(BirthDate);
			birthCalendar.setTime(birthDate);
			Date effectiveDate = new Date();
			effectiveCalendar.setTime(effectiveDate);

			age = effectiveCalendar.get(Calendar.YEAR) - birthCalendar.get(Calendar.YEAR);
			if (birthCalendar.get(Calendar.MONTH) > effectiveCalendar.get(Calendar.MONTH))
			{
				age = age - 1;
			}
			else if (birthCalendar.get(Calendar.MONTH) == effectiveCalendar.get(Calendar.MONTH))
			{
				if (birthCalendar.get(Calendar.DAY_OF_MONTH) > effectiveCalendar.get(Calendar.DAY_OF_MONTH))
				{
					age = age - 1;
				}
			}
		}
		catch (ParseException e)
		{
			e.printStackTrace();
		}
		return age;
	}

	public static void main(String[] args) throws Exception
	{
//		String ssss = "\u8001\u5E08\u544A\u8BC9\u6211\u4EEC\uFF0C";
//		System.out.println(loadConvert(ssss.toCharArray(), 0, ssss.length(), new char[0]));
//		System.out.println(Integer.valueOf("-2"));
		
		FileReader file = new FileReader("c://INS01_201208218.TXT");
		BufferedReader br = new BufferedReader(file);
		StringBuffer str = new StringBuffer();
		String fileLineStr="";  
		while (br.ready()) {
			fileLineStr = br.readLine();//读取一行
			fileLineStr = StringUtilss.checkXmlChar(fileLineStr);
			System.out.println(fileLineStr);
			str.append(fileLineStr);
		}
		BufferedWriter bw = new BufferedWriter(new FileWriter(new File("C://new.txt"), true));
		bw.write(str.toString());
		bw.flush();
		bw.close();
	}

	private static String loadConvert(char[] in, int off, int len, char[] convtBuf)
	{
		if (convtBuf.length < len)
		{
			int newLen = len * 2;
			if (newLen < 0)
			{
				newLen = Integer.MAX_VALUE;
			}
			convtBuf = new char[newLen];
		}
		char aChar;
		char[] out = convtBuf;
		int outLen = 0;
		int end = off + len;

		while (off < end)
		{
			aChar = in[off++];
			if (aChar == '\\')
			{
				aChar = in[off++];
				if (aChar == 'u')
				{
					// Read the xxxx
					int value = 0;
					for (int i = 0; i < 4; i++)
					{
						aChar = in[off++];
						switch (aChar)
						{
						case '0':
						case '1':
						case '2':
						case '3':
						case '4':
						case '5':
						case '6':
						case '7':
						case '8':
						case '9':
							value = (value << 4) + aChar - '0';
							break;
						case 'a':
						case 'b':
						case 'c':
						case 'd':
						case 'e':
						case 'f':
							value = (value << 4) + 10 + aChar - 'a';
							break;
						case 'A':
						case 'B':
						case 'C':
						case 'D':
						case 'E':
						case 'F':
							value = (value << 4) + 10 + aChar - 'A';
							break;
						default:
							throw new IllegalArgumentException("Malformed \\uxxxx encoding.");
						}
					}
					out[outLen++] = (char) value;
				}
				else
				{
					if (aChar == 't') {
						aChar = '\t';
					} else if (aChar == 'r') {
						aChar = '\r';
					} else if (aChar == 'n') {
						aChar = '\n';
					} else if (aChar == 'f') {
						aChar = '\f';
					}
					out[outLen++] = aChar;
				}
			}
			else
			{
				out[outLen++] = (char) aChar;
			}
		}
		return new String(out, 0, outLen);
	}

}
